// 依赖;
import { SyntheticEvent, useState } from 'react';
import dayjs from "dayjs"
import { EventEmitter } from 'events'
import { nanoid } from "nanoid"
import { modeType } from './interface';
import { $Http } from '../network';
import { message } from 'antd';

// 常量
export const $constantList = {
    proApi: "222.212.85.72:",
    stationStatusColor: ["#52C41A", "#FAAD14", "#FF4D4F", "#999999"]
}
// api
export const $envApi = (isStatic = false) => {
    return isStatic ? `${$constantList["proApi"]}18848/static/images/` : process.env.NODE_ENV === "development" ? "/api" : `http://${$constantList["proApi"]}8848/`
}

// 生成uuid
export const $nanoid_uuid = () => {
    return nanoid()
}
// websocket地址
export const $websocketUrl = `ws://${process.env.NODE_ENV === "development" ? "192.168.1.20:8000" : $constantList["proApi"]}8848/websocket`



// 图表数据
export const $echartsData = {
    zoomAxisHeight: 60, // 缩放轴的高度
    zoomAxisConfigureData: { //缩放轴配置
        start: 0,
        end: 100,
        bottom: 9,
        handleSize: 49,
        handleStyle: {
            borderColor: "#BFBFBF",
            color: "#F7F7F7"
        },
        dataBackground: {
            lineStyle: {
                color: 'rgba(0, 0, 0, 0.3)',
            },
            areaStyle: {
                color: 'rgba(0, 0, 0, 0)',
            },
        },
        selectedDataBackground: {
            lineStyle: {
                color: 'rgba(0, 0, 0, 0.3)',
            },
            areaStyle: {
                color: 'rgba(0, 0, 0, 0.05)',
            },
        },
        moveHandleSize: 0,
        borderColor: "rgba(0, 0, 0, 0)",
        fillerColor: 'rgba(0, 0, 0, 0.05)',
        backgroundColor: 'rgba(0, 0, 0, 0.05)',
    },

    chartLineColorList: ["#5B8FF9", "#61DDAA", "#65789B", "#F6BD16", "#7262FD", "#78D3F8", "#9661BC", "#F6903D", "#008685", "#F08BB4"], // 折线图颜色列表
    charWarningLineColorList: ["#FF4D4F", "#FAAD14"], // 图表预警线颜色列表

}
// 头部操作下拉框选项数据
export const $selectOptionData = {
    all: { label: "全部" },  // 全部
    monitoringDevice: [  // 监测装置
        { label: "固定装置", },
        { label: "便携装置", }
    ],
    monitoringType: [  // 监测类型
        { label: "主变", },
        { label: "线路", }
    ],
    gender: [
        { label: "男" },
        { label: "女" }
    ],
    voltageLevel: [
        { label: "500kV" },
        { label: "220kV" },
        { label: "110kV" },
    ],
    type: [
        { label: "金属护套电流" },
        { label: "回流线电流" },
        { label: "地网对地电位" },
    ],
    dataType: [
        { label: "金属护套电流" },
        { label: "回流线电流" },
        { label: "地网对地电位" },
        { label: "中性点直流" },
        { label: "中性点交流" },
        { label: "架空地线电流" },
    ],
    warningLevel: [
        { label: "一级" },
        { label: "二级" },
    ]
}

// 头部操作按钮数据
export const $headerOperationBtnData = (name: string, type: string, data = {}, isPower = $PowerSetting()["basePower"]) => { // 查询按钮
    return {
        name,
        type,
        ...data,
        isPower
    }
}
// 头部操作条件数据
export const $headerOperationConditionData = {
    monitoringDevice: (isHideAll = false, key: string = "monitorDevice", label: string = "监测装置") => { // 监测装置        
        const optionList = isHideAll ? $selectOptionData["monitoringDevice"] : [$selectOptionData["all"], ...$selectOptionData["monitoringDevice"]]
        return {
            label,
            key,
            type: "select",
            optionList
        }
    },
    monitoringType: (label: string = "监测类型") => { // 监测类型
        return {
            label,
            key: "monitoringType",
            type: "select",
            isNoDefault: true,
            optionList: [
                $selectOptionData["all"],
                ...$selectOptionData["monitoringType"]
            ]
        }
    },
    singleBtn: (label: string, monitoringType?: string) => {  // 单选按钮
        return {
            label,
            type: "singleBtn",
            monitoringType,
            monitorModalName: `选择${label}`,
        }
    },

    multipleBtn: (label: string, monitoringType: string) => {  // 多选按钮
        return {
            label,
            key: "",
            type: "multipleBtn",
            monitoringType: monitoringType,
            monitorModalName: `选择${label}`,
        }
    },

    dateTimePickerRange: (label: string, keyList: Array<string>) => {  // 时间区间选择
        return {
            label,
            keyList,
            type: "dateTimePickerRange",
        }
    },
    input: (label: string, key: string) => {
        return {
            label,
            key,
            type: "input"
        }
    },

    dataType: (label?: string, len?: number) => {
        return {
            label: label ?? "数据类型",
            key: "dataType",
            type: "select",
            optionList: [
                $selectOptionData["all"],
                ...(len ? $selectOptionData["dataType"].slice(0, len) : $selectOptionData["dataType"]),

            ]
        }
    },
    voltageLevel: {
        label: "电压等级",
        key: "volLevel",
        type: "select",
        optionList: [
            $selectOptionData["all"],
            ...$selectOptionData["voltageLevel"],
        ]

    },
    warningLevel: {
        label: "预警等级",
        key: "warningLevel",
        type: "select",
        optionList: [
            $selectOptionData["all"],
            ...$selectOptionData["warningLevel"]
        ]
    },
    assessmentType: {
        label: "评估类型",
        key: "评估类型",
        type: "select",
        optionList: [
            $selectOptionData["all"]
        ]
    },
    communicationStatus: {
        label: "通讯状态",
        key: "通讯状态",
        type: "select",
        optionList: [
            $selectOptionData["all"]
        ]
    },
    currentStatus: {
        label: "当前状态",
        key: "当前状态",
        type: "select",
        optionList: [
            $selectOptionData["all"]
        ]
    },
    modeStatus: {
        label: "模式状态",
        key: "模式状态",
        type: "select",
        optionList: [
            $selectOptionData["all"]
        ]
    },
    samplingRate: {
        label: "采样率",
        key: "采样率",
        type: "select",
        optionList: [
            $selectOptionData["all"]
        ]
    },
    gender: {
        label: "性别",
        key: "gender",
        type: "select",
        optionList: [
            $selectOptionData["all"],
            ...$selectOptionData["gender"],

        ]
    },
}
// 过滤组织层级
export const $FilterOrganizationRank = (value: string) => {
    let rank = ""
    switch (value) {
        case "团队":
            rank = "team"
            break
        case "部门":
            rank = "department"
            break
        case "职位":
            rank = "position"
            break
        case "账号":
            rank = "user"
            break
    }
    return rank
}
// 组织级别列表
export const $oganizationRankList = ["团队", "部门", "职位"]

// 切割组织的名称和ID
export const $SplitOganizationNameAndID = (value: string) => {
    // [name,ID]
    return value.split("-").slice(-1)[0].split("*")
}
// 权限分配
export const $PowerSetting = (id?: number | string) => {
    // const userID = sessionStorage.userID
    const teamID = sessionStorage.teamID
    const departmentID = sessionStorage.departmentID
    const positionID = sessionStorage.positionID
    const power = sessionStorage.power
    const basePower = power !== "普通用户"
    const superPower = power === "超级管理员"
    return {
        basePower,  // 基础权限
        superPower, // 超级权限
        userOperation: superPower, // 用户操作
        teamDelete: id != teamID, // 团队删除
        departmentDelete: id != departmentID, // 部门删除
        positionDelete: id != positionID, // 职位删除
    }
}
// 科学计数法
export const $ScientificNotation = (num: number | string, separators: string = ",") => {
    num ??= 0
    return num
        .toString()
        .replace(/\d+/, (n) => {
            return n.replace(/(\d)(?=(?:\d{3})+$)/g, `$1${separators}`);
        });
}

// 获取两个日期间的日期
export const $RangeDateList = (startDate: string, endDate: string) => {
    let tempStartDate = dayjs(startDate).clone()
    let tempEndDate = dayjs(endDate)
    const rangeDateList: Array<string> = []
    while (tempStartDate.isBefore(tempEndDate) || tempStartDate.isSame(tempEndDate)) {
        rangeDateList.push(tempStartDate.format("YYYY-MM-DD HH:mm:ss"))
        tempStartDate = tempEndDate.add(1, "second")
    }
    return rangeDateList
}
export const $JudgePortableDevice = (type: string, mainTransformerResult: any, lineResult: any) => {
    return type === "主变（便携装置）" ? mainTransformerResult : type === "线路（便携装置）" && lineResult
}

// 预警等级颜色
export const $WarningLevelColor = (value: string) => {
    let color = ""
    switch (value) {
        case "一级":
            color = "#FF4D4F"
            break;
        case "二级":
            color = "#FAAD14"
            break;
    }
    return color
}


// 阻止冒泡
export const $StopPropagation = (e: SyntheticEvent) => {
    e.stopPropagation()
    e.nativeEvent.stopImmediatePropagation()
}

// 页面刷新监听
export const $beforeunload = (socket: any, uuid: string, module: string) => {
    window.addEventListener("beforeunload", () => {
        socket.send(JSON.stringify(
            {
                uuid,
                type: "close",
                module
            }
        ))
        socket.close()
    })
}

//  判断模式
export const $switch_mode = (value: modeType | undefined, multipleResult: any, singleResult: any) => {
    let result: any
    switch (value) {
        case "multiple":
        case undefined:
            result = multipleResult
            break
        case "single":
            result = singleResult
    }
    return result
}
//  判断标签
export const $switch_tagName = (value: string, multipleAndSameResult: any, singleAndMultipleResult: any, singleAndTwinResult: any) => {
    let result: any
    switch (value) {
        case "多主变同指标":
        case "多线路同指标":
            result = multipleAndSameResult
            break
        case "单主变多指标":
        case "单线路多指标":
            result = singleAndMultipleResult
            break
        case "单主变双时段":
        case "单线路双时段":
            result = singleAndTwinResult
            break
    }
    return result
}

// 数据导出
export const $export_excel = (typeName: string, list: Array<number>) => {
    $Http("export", { typeName, id: list }).then((res: any) => {
        const blob = new Blob([`\ufeff${res}`], { type: 'text/csv;charset=utf-8;' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.setAttribute("href", url);
        link.setAttribute("download", `${typeName.split("/").splice(-1)}${dayjs().format("YYYYMMDDHHmmss")}.csv`);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
        message.open({
            type: 'success',
            content: "导出成功！",
        })
    })
}

// 判断指标
export const $switch_index = (value: string) => {
    let label = ""
    switch (value) {
        case "DC1":
            label = "中性点直流\nDC1（A）"
            break;
        case "AC":
            label = "中性点交流\nAC（A）"
            break;
        case "NI":
            label = "振动速度\nVA（mm）s)"
            break;
        case "VA":
            label = "噪声强度\nNI（dB）"
            break;
        case "EP1":
            label = "地表电位\nEP1（V）"
            break;
        case "金属护套电流":
            label = "金属护套\n电流（A）"
            break;
        case "回流线电流":
            label = "回流线\n电流（A）"
            break;
        case "架空地线电流":
            label = "架空地线\n电流（A）"
            break;
    }
    return label
}
// 跨组件通讯
// 发送：.emit(name,data)
// 接收：.addListener((res)=>{}) 
// 销毁 .removeAllListeners(name)
export const $eventBus = new EventEmitter();

export const $EventBus_on = (data: object) => {
    Object.keys(data).forEach((item: string) => {
        $eventBus.on(item, data[item])
    })
}

export const $EventBus_off = (data: object) => {
    Object.keys(data).forEach((item: string) => {
        $eventBus.off(item, data[item])
    })
}
